package com.server.web.controller.tool;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.server.biz.domain.BizUserinfo;
import com.server.biz.dto.BizUserinfoDto;
import com.server.biz.dto.BizUserinfoLoginDto;
import com.server.biz.service.IBizUserinfoService;
import com.server.common.annotation.Log;
import com.server.common.core.controller.BaseController;
import com.server.common.core.domain.AjaxResult;
import com.server.common.core.redis.RedisCache;
import com.server.common.enums.BusinessType;
import com.server.common.utils.DateUtils;
import com.server.common.utils.ServletUtils;
import com.server.common.utils.SnowFlake;
import com.server.common.utils.ip.IpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * 用户信息Controller
 *
 * @author server
 * @date 2021-12-18
 */
@Api(tags ="用户信息管理")
@RestController
@RequestMapping("/api/userinfo")
public class UserinfoApiController extends BaseController {
    @Autowired
    private IBizUserinfoService bizUserinfoService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取用户信息详细信息
     */
    @ApiOperation("获取用户信息详细信息")
    @GetMapping(value = "/{userid}")
    public AjaxResult getInfo(@PathVariable("userid") String userid) {
        LambdaQueryWrapper<BizUserinfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BizUserinfo::getDelFlag,"0")
                .eq(BizUserinfo::getUserid,userid)
                .last("limit 1");
        BizUserinfo bizUserinfo = bizUserinfoService.getOne(lambdaQueryWrapper);
        if(bizUserinfo==null){
            return AjaxResult.error(10001,"用户不存在");
        }
        return AjaxResult.success(bizUserinfo);
    }

    /**
     * 新增用户信息
     */
    @ApiOperation("用户登录")
    @PostMapping(value = "/login")
    public AjaxResult login(@RequestBody BizUserinfoLoginDto userinfoDto) {
        String date = DateUtils.getTime();
        if(!Pattern.compile("^[1]\\d{10}$").matcher(userinfoDto.getPhone()).matches()){
            return AjaxResult.error("手机号码不合法");
        }
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());

        if(redisCache.getCacheObject(ip+"_login")!=null){
            return AjaxResult.error("操作过于频繁,请稍后再试！");
        }
        //限制频繁登录
        redisCache.setCacheObject(ip+"_login", DateUtils.parseDateToStr("yyyy-MM-dd mm:HH:ss",new Date()), 5, TimeUnit.SECONDS);
        String verifyCode = redisCache.getCacheObject(userinfoDto.getPhone()+"_verifyCode");
        if(verifyCode!=null && verifyCode.equals(userinfoDto.getVcode())){
            String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
            redisCache.setCacheObject(userinfoDto.getPhone()+"_token", uuid, 7, TimeUnit.DAYS);
            LambdaQueryWrapper<BizUserinfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(BizUserinfo::getDelFlag,"0")
                    .eq(BizUserinfo::getPhone,userinfoDto.getPhone())
                    .last("limit 1");
            BizUserinfo bizUserinfo = bizUserinfoService.getOne(lambdaQueryWrapper);
            if(bizUserinfo==null){
                return AjaxResult.error(10001,"用户不存在");
            }
            BizUserinfoDto bizUserinfoDto = new BizUserinfoDto();
            BeanUtils.copyProperties(bizUserinfo,bizUserinfoDto);
            return AjaxResult.success(bizUserinfoDto);
        }else {
            System.out.println(date+"【验证短信】-----------------------response  toString is : 验证失败！验证码不匹配");
            return AjaxResult.error(10001,"验证码不正确!");
        }
    }

    /**
     * 新增用户信息
     */
    @ApiOperation("用户报名")
    @Log(title = "用户报名", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody BizUserinfoDto userinfoDto) {
        LambdaQueryWrapper<BizUserinfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BizUserinfo::getDelFlag,"0")
                .eq(BizUserinfo::getPhone,userinfoDto.getPhone())
                .last("limit 1");
        BizUserinfo bizUserinfo2 = bizUserinfoService.getOne(lambdaQueryWrapper);
        if(bizUserinfo2!=null){
            return AjaxResult.error("手机号码被占用");
        }
        BizUserinfo bizUserinfo = new BizUserinfo();
        BeanUtils.copyProperties(userinfoDto,bizUserinfo);
        bizUserinfo.setUserid(SnowFlake.nextId() + "");
        bizUserinfo.setCreateTime(new Date());
        bizUserinfo.setStatus("待审核");
        return toAjax(bizUserinfoService.save(bizUserinfo));
    }

    /**
     * 修改用户信息
     */
    @ApiOperation("修改用户报名信息")
    @Log(title = "修改用户报名信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/edit")
    public AjaxResult edit(@RequestBody BizUserinfoDto userinfoDto) {
        BizUserinfo bizUserinfo2 = bizUserinfoService.getById(userinfoDto.getUserid());
        if(bizUserinfo2==null || bizUserinfo2.getStatus().equals("审核通过")){
            return AjaxResult.error("用户不允许修改");
        }
        BizUserinfo bizUserinfo = new BizUserinfo();
        BeanUtils.copyProperties(userinfoDto,bizUserinfo);
        bizUserinfo.setUpdateTime(new Date());
        bizUserinfo.setPhone(null);
        bizUserinfo.setStatus("待审核");
        return toAjax(bizUserinfoService.updateById(bizUserinfo));
    }

}
